## This file runs QCA on the simulated data

## Run below if not running files in a single session to load data created in
## sim_make-data.R; otherwise can skip
if ( TRUE ) {
  # Load simulation data
  load("sim/out/simData.rda")
  load("sim/out/simIndices.rda")
}

## Run QCA -----------------------
allRuleSets_QCA <- list()
for(i in 1:5){ # Loop through all DGP settings except probabilistic J=20
  ruleSet_QCA <- list()
  for(j in 1:length(allIndices)){ # Loop through all sample sizes
    print(cat("i=", i, ", j=", j))
    ruleSet_QCA[[j]] <- foreach (k=1:length(allData[[i]])) %dopar% {
      data <- allData[[i]][[k]]
      df <- data[allIndices[[j]][[k]],-ncol(data)]
      Y <- data[allIndices[[j]][[k]], ncol(data)] # Last column is Y
      tt <- truthTable(cbind(df, Y), outcome="Y", incl.cut = .67, conditions=colnames(df))
      minimize(tt, include="?", row.dom = TRUE, min.pin = TRUE, first.min = T)$solution[[1]]
    } # end k
  } # end j
  allRuleSets_QCA[[i]] <- ruleSet_QCA
} # end i

# Run QCA on probabilistic data for J=20; stop at N=100 (N>=250 is infeasible)
i <- 6
ruleSet_QCA <- list()
for(j in 1:2){ # Loop through all sample sizes
  print(cat("i=", i, ", j=", j))
  ruleSet_QCA[[j]] <- foreach (k=1:length(allData[[i]])) %dopar% {
    data <- allData[[i]][[k]]
    df <- data[allIndices[[j]][[k]],-ncol(data)]
    Y <- data[allIndices[[j]][[k]], ncol(data)] # Last column is Y
    tt <- truthTable(cbind(df, Y), outcome="Y", incl.cut = .67, conditions=colnames(df))
    minimize(tt, include="?", row.dom = TRUE, min.pin = TRUE, first.min = T)$solution[[1]]
  } # end k
}
allRuleSets_QCA[[i]] <- ruleSet_QCA

save(allRuleSets_QCA, file="sim/out/sim_out_QCA.rda")